---
title: "R_fig_A5"
author: "Loreto Cox & Carmen Le Foulon"
date: "2024-01-29"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
library(readxl)
```

# Info

Replication for Figure A5

# Data
```{r}
## data for electoral results of presidential elections
d<-read.csv("data/pres_hist.csv", sep = ";")

## subset to 2017, runnoff
d<-d[d$Año.de.Elección==2017&d$Votación.Presidencial=="SEGUNDA VOTACIÓN",]

## null, blank, and total votes by municipality
null<- tapply(d$Votos.Totales[d$Candidato..a.=="VOTOS NULOS"], d$Comuna[d$Candidato..a.=="VOTOS NULOS"],sum)
blank<-tapply(d$Votos.Totales[d$Candidato..a.=="VOTOS EN BLANCO"], d$Comuna[d$Candidato..a.=="VOTOS EN BLANCO"],sum)
total<-tapply(d$Votos.Totales,d$Comuna,sum)

##Create database with all three
runoff<-as.data.frame(cbind(null, blank, total))
runoff$comuna<-rownames(runoff)

## Database with municipality names, districts and seats
comunas_dist<-read.csv("data/comunas_dist.csv", sep=";")

## Merge with runoff
all<-full_join(runoff,comunas_dist)
```

# Figure A5

## Figure A5 A

```{r}

## Invalid voting by House district magnitude
null_seats_dip<-tapply(all$null,all$dip_dist_seats,sum,na.rm=T)/tapply(all$total,all$dip_dist_seats,sum,na.rm=T)
blank_seats_dip<-tapply(all$blank,all$dip_dist_seats,sum,na.rm=T)/tapply(all$total,all$dip_dist_seats,sum,na.rm=T)
invalid_seats_dip<-null_seats_dip+blank_seats_dip

## Figure A5 (A)	 
plot(100*null_seats_dip, col="blue", pch=19, ylim=c(0,1.5),cex=1.2, 
     ylab="Share of votes (%)",xaxt="n",xlab="District magnitude")
#main= "Invalid Voting by House District Magnitude, 2017 runoff", 
xnames<-names(null_seats_dip)
axis(1, at=1:length(xnames), labels=xnames) 
points(100*blank_seats_dip, col="red", pch=24, cex=1.2)
legend(legend=c("Nulls","Blanks"), col = c("blue", "red"),pch=c(19,24),"topright")


```

## Figure A5 B

```{r}

##Invalid voting by Senate district magnitude
null_seats_sen<-tapply(all$null,all$sen_dist_seats,sum,na.rm=T)/tapply(all$total,all$sen_dist_seats,sum,na.rm=T)
blank_seats_sen<-tapply(all$blank,all$sen_dist_seats,sum,na.rm=T)/tapply(all$total,all$sen_dist_seats,sum,na.rm=T)
invalid_seats_sen<-null_seats_sen+blank_seats_sen

## Figure A5 (B)	
plot(100*null_seats_sen, col="blue", pch=19, ylim=c(0,1.5), cex=1.2, 
     ylab="Share of votes (%)",xaxt="n",xlab="District magnitude")
#,main= "Invalid Voting by Senate District Magnitude, 2017 runoff",
xnames<-names(null_seats_sen)
axis(1, at=1:length(xnames), labels=xnames) 
points(100*blank_seats_sen, col="red", pch=24, cex=1.2)
legend(legend=c("Nulls","Blanks"), col = c("blue", "red"),pch=c(19,24),"topright")


```

